package com.example.lastwork.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.Date;
import java.util.Set;

@Entity
@Getter
@Setter
@DiscriminatorValue("0")
public class Customer extends User {
    @JsonIgnore
    @OneToMany(mappedBy = "customer",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties("customer")
    @JsonBackReference
    private Set<Orders> orders;

    // 创建新订单
    public Orders createNewOrder(Long shopId){
        if(getUnpaidOrder(shopId) != null){
            return getUnpaidOrder(shopId);
        }
        Orders order = new Orders();
        order.setTotal(0.0);
        order.setStatus(0);
        order.setCustomer(this);
        orders.add(order);
        return order;
    }

    private Orders getUnpaidOrder(Long shopId) {
        if (getOrders() != null) {
            for (Orders order : getOrders()) {
                if (order.getShop().getId().equals(shopId) && order.getStatus() == 0) {
                    return order;
                }
            }
        }
        return null;
    }

    public Orders cancelUnpaidOrder(Long shopId) {
        Orders order = getUnpaidOrder(shopId);
        if (order != null) {
            order.setIsDeleted(1);
            order.setDeletedTime(new Date());
            orders.remove(order);
            return order;
        } else {
            return null;
        }
    }
}
